package myJs.admin

import scala.scalajs.js.Dynamic.{global => g}
import myJs.Utils.layer
import myJs.myPkg._
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{FormData, document}
import scalatags.Text.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.myPkg.jquery._
import myJs.Implicits._
import myJs.Implicits._
import myJs.Tool

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("UserManage")
object UserManage {

  @JSExport("init")
  def init = {
    $("#table").bootstrapTable()
    refreshUser()
    bootStrapValidator

  }

  @JSExport("refreshUser")
  def refreshUser(f: () => js.Any = () => ()) = {
    val url = g.jsRoutes.controllers.AdminController.getAllUser().url.toString
    Ajax.get(url = s"${url}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val data = xhr.responseText.toJArJDS
      $("#table").bootstrapTable("load", data)
      f()
    }
  }

  @JSExport("operateFmt")
  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val resetStr = a(
        title := "重置",
        onclick := s"UserManage.resetShow('" + row("id") + "')",
        cursor.pointer,
        span(
          em(cls := "fa fa-repeat")
        )
      )
      val deleteStr = a(
        title := "删除",
        cursor.pointer,
        onclick := s"UserManage.deleteData('" + row("id") + "')",
        target := "_blank",
        span(
          em(cls := "fa fa-close")
        )
      )
      Array(resetStr, deleteStr).mkString("&nbsp;")
  }

  @JSExport("resetShow")
  def resetShow(id: String) = {
    val formId = "updateForm"
    val url = g.jsRoutes.controllers.AdminController.getUserById().url.toString
    Ajax.get(url = s"${url}?id=${id}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val data = xhr.responseText
      val rs = data.toJDS
      Tool.fillByNames(rs, formId)
      $("#updateModal").modal("show")
    }
  }

  @JSExport("update")
  def update = {
    val formId = "updateForm"
    val bv = $(s"#${formId}").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val data = $(s"#${formId}").serialize()
      val index = layer.alert(Tool.myElement, Tool.layerOptions)
      val url = g.jsRoutes.controllers.AdminController.updateUser().url.toString
      Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/x-www-form-urlencoded"),
        responseType = "application/json").map { xhr =>
        val json = xhr.response.toJDS
        refreshUser { () =>
          layer.close(index)
          $("#updateModal").modal("hide")
          bv.resetForm(true)
          swal(SwalOptions(title = "成功", text = "密码重置成功!", `type` = "success"))
        }
      }
    }
  }

  @JSExport("add")
  def add = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val data = $(s"#form").serialize()
      val index = layer.alert(Tool.myElement, Tool.layerOptions)
      val url = g.jsRoutes.controllers.AdminController.addUser().url.toString
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      Ajax.post(url = s"${url}", data = formData,
        responseType = "application/json").map { xhr =>
        val json = xhr.response.toJDS
        refreshUser { () =>
          layer.close(index)
          $("#addModal").modal("hide")
          bv.resetForm(true)
          swal(SwalOptions(title = "成功", text = "新增成功!", `type` = "success"))
        }
      }
    }
  }

  @JSExport("addShow")
  def addShow = {
    $("#addModal").modal("show")
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.AdminController.userNameCheck().url.toString
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "name" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "用户名不能为空！"
            ),
            "remote" -> js.Dictionary(
              "message" -> "用户名已存在！",
              "url" -> url,
              "delay" -> 1000,
              "type" -> "POST",
            ),
          )
        ),
        "password" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "密码不能为空！"
            ),
          )
        ),
      )
    )
    g.$("#form").bootstrapValidator(dict)
    updateFormBootStrapValidator
  }

  @JSExport("deleteData")
  def deleteData(id: String) = {
    val options = SwalOptions(
      title = "",
      text = "确定要删除此数据吗？",
      `type` = "warning",
      showCancelButton = true,
      showConfirmButton = true,
      confirmButtonClass = Tool.confirmButtonClass,
      confirmButtonText = "确定",
      closeOnConfirm = false,
      cancelButtonText = "取消",
      showLoaderOnConfirm = true,
      cancelButtonClass = Tool.cancelButtonClass
    )
    swalRaw(options, () => {
      val url = g.jsRoutes.controllers.AdminController.deleteUserById().url.toString
      Ajax.delete(url = s"${url}?id=${id}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
        val data = xhr.response
        refreshUser { () =>
          swal(SwalOptions(title = "成功", text = "删除成功", `type` = "success"))
        }
      }
    })
  }


  def updateFormBootStrapValidator = {
    val url = g.jsRoutes.controllers.AdminController.userNameCheck().url.toString
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "password" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "密码不能为空！"
            ),
          )
        ),
      )
    )
    g.$("#updateForm").bootstrapValidator(dict)
  }


}
